package com.guli.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.guli.cart.FeignServer.ProductFeignService;
import com.guli.cart.conf.CartInterceptor;
import com.guli.cart.service.CartService;
import com.guli.cart.vo.CartItemVo;
import com.guli.cart.vo.UserInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author: 朱财艺
 * @date : 2022/02/10
 * @Description:
 */
@Service
public class CartServiceImpl implements CartService {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;



    @Override
    public CartItemVo addToCart(Long skuId, Integer num) {


        BoundHashOperations<String, Object, Object> op = getOp();

        Object o = op.get(skuId+"");
        if (o==null){
            CartItemVo cartItemVo = productFeignService.cartById(skuId);
            cartItemVo.setCount(cartItemVo.getCount()+num);
            String jsonString = JSON.toJSONString(cartItemVo);
            op.put(skuId+"",jsonString);
            return cartItemVo;
        }else {

            CartItemVo cartItemVo = JSON.parseObject(o.toString(), new TypeReference<CartItemVo>() {
            });

            return cartItemVo;

        }


    }

    private BoundHashOperations<String, Object, Object> getOp() {

        UserInfoVo userInfoVo = CartInterceptor.threadLocal.get();
        if (!StringUtils.isEmpty(userInfoVo.getUserId())){
            //普通用户

            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps("gulimall:cart:" + userInfoVo.getUserId());

            return ops;
        }else {

            //临时用户
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps("gulimall:cart:" + userInfoVo.getUserKey());

            return ops;
        }
    }
}
